document.addEventListener("DOMContentLoaded", function () {
    // 天气预报功能
    const cityInput = document.getElementById("cityInput");
    const getWeatherBtn = document.getElementById("getWeather");
    const getLocationBtn = document.getElementById("getLocation");
    const weatherResult = document.getElementById("weatherResult");

    // 使用OpenWeatherMap API (需要替换为您的API key)
    const apiKey = "5c2859fa4f675526f73369da29a9c5aa";
    
    getWeatherBtn.addEventListener("click", fetchWeather);
    getLocationBtn.addEventListener("click", getLocationWeather);
    cityInput.addEventListener("keypress", function (e) {
        if (e.key === "Enter") fetchWeather();
    });

    async function fetchWeather() {
        const city = cityInput.value.trim();
        if (!city) {
            alert("请输入城市名称");
            return;
        }

        try {
            const response = await fetch(
                `https://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=${apiKey}&lang=zh_cn`
            );

            if (!response.ok) {
                throw new Error("城市未找到，请检查名称是否正确");
            }

            const data = await response.json();
            displayWeather(data);

            // 获取天气预报
            const forecastResponse = await fetch(
                `https://api.openweathermap.org/data/2.5/forecast?q=${city}&units=metric&appid=${apiKey}&lang=zh_cn&cnt=5`
            );

            if (forecastResponse.ok) {
                const forecastData = await forecastResponse.json();
                displayForecast(forecastData);
            }
        } catch (error) {
            alert(error.message);
        }
    }

    function getLocationWeather() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(
                async (position) => {
                    const { latitude, longitude } = position.coords;
                    try {
                        const response = await fetch(
                            `https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&units=metric&appid=${apiKey}&lang=zh_cn`
                        );

                        if (!response.ok) {
                            throw new Error("无法获取当前位置的天气信息");
                        }

                        const data = await response.json();
                        cityInput.value = data.name;
                        displayWeather(data);

                        // 获取天气预报
                        const forecastResponse = await fetch(
                            `https://api.openweathermap.org/data/2.5/forecast?lat=${latitude}&lon=${longitude}&units=metric&appid=${apiKey}&lang=zh_cn&cnt=5`
                        );

                        if (forecastResponse.ok) {
                            const forecastData = await forecastResponse.json();
                            displayForecast(forecastData);
                        }
                    } catch (error) {
                        alert(error.message);
                    }
                },
                (error) => {
                    alert("无法获取您的位置: " + error.message);
                }
            );
        } else {
            alert("您的浏览器不支持地理位置功能");
        }
    }

    function displayWeather(data) {
        document.getElementById("cityName").textContent = data.name;
        document.getElementById("temperature").textContent = Math.round(
            data.main.temp
        );
        document.getElementById("weatherDesc").textContent =
            data.weather[0].description;
        document.getElementById("humidity").textContent =
            data.main.humidity + "%";
        document.getElementById("windSpeed").textContent =
            (data.wind.speed * 3.6).toFixed(1) + " km/h";

        // 设置天气图标
        const weatherIcon = document.getElementById("weatherIcon");
        const iconClass = getWeatherIconClass(
            data.weather[0].id,
            data.weather[0].icon
        );
        weatherIcon.className = `wi ${iconClass}`;

        // 转换日出日落时间
        const sunriseTime = new Date(data.sys.sunrise * 1000);
        const sunsetTime = new Date(data.sys.sunset * 1000);
        document.getElementById("sunrise").textContent =
            formatTime(sunriseTime);
        document.getElementById("sunset").textContent = formatTime(sunsetTime);

        // 显示天气结果区域
        weatherResult.style.display = "flex";
    }

    function displayForecast(data) {
        const forecastContainer = document.getElementById("weatherForecast");
        forecastContainer.innerHTML = "";

        // 显示5天的预报 (每8小时一个数据点，我们每天取中午的数据)
        for (let i = 0; i < 5; i++) {
            const forecast = data.list[i * 8]; // 调整为每天一个数据点

            const forecastItem = document.createElement("div");
            forecastItem.className = "forecast-item";

            const forecastDay = document.createElement("div");
            forecastDay.className = "forecast-day";
            forecastDay.textContent = i === 0 ? "今天" : formatDay(forecast.dt);

            const forecastIcon = document.createElement("i");
            const iconClass = getWeatherIconClass(
                forecast.weather[0].id,
                forecast.weather[0].icon
            );
            forecastIcon.className = `wi ${iconClass}`;

            const forecastTemp = document.createElement("div");
            forecastTemp.className = "forecast-temp";
            forecastTemp.textContent = `${Math.round(
                forecast.main.temp_min
            )}° / ${Math.round(forecast.main.temp_max)}°`;

            forecastItem.appendChild(forecastDay);
            forecastItem.appendChild(forecastIcon);
            forecastItem.appendChild(forecastTemp);
            forecastContainer.appendChild(forecastItem);
        }
    }

    function getWeatherIconClass(weatherId, icon) {
        // 根据天气代码返回对应的Weather Icons类
        if (weatherId >= 200 && weatherId < 300) {
            return "wi-thunderstorm";
        } else if (weatherId >= 300 && weatherId < 400) {
            return "wi-sprinkle";
        } else if (weatherId >= 500 && weatherId < 600) {
            return icon.includes("d") ? "wi-day-rain" : "wi-night-rain";
        } else if (weatherId >= 600 && weatherId < 700) {
            return "wi-snow";
        } else if (weatherId >= 700 && weatherId < 800) {
            return "wi-fog";
        } else if (weatherId === 800) {
            return icon.includes("d") ? "wi-day-sunny" : "wi-night-clear";
        } else if (weatherId > 800) {
            return icon.includes("d") ? "wi-day-cloudy" : "wi-night-cloudy";
        }
        return "wi-day-sunny";
    }

    function formatTime(date) {
        return date.toLocaleTimeString([], {
            hour: "2-digit",
            minute: "2-digit",
        });
    }

    function formatDay(timestamp) {
        const date = new Date(timestamp * 1000);
        return date.toLocaleDateString([], { weekday: "short" });
    }

    // BMI计算器功能
    const heightInput = document.getElementById("height");
    const weightInput = document.getElementById("weight");
    const calculateBtn = document.getElementById("calculateBmi");
    const resetBtn = document.getElementById("resetBmi");
    const bmiResult = document.getElementById("bmiResult");
    const bmiValue = document.getElementById("bmiValue");
    const bmiCategory = document.getElementById("bmiCategory");
    const bmiIndicator = document.getElementById("bmiIndicator");
    const bmiTips = document.getElementById("bmiTips");

    calculateBtn.addEventListener("click", calculateBMI);
    resetBtn.addEventListener("click", resetBMI);

    function calculateBMI() {
        const height = parseFloat(heightInput.value);
        const weight = parseFloat(weightInput.value);

        // 验证输入
        if (!height || height < 100 || height > 250) {
            alert("请输入有效的身高 (100-250cm)");
            return;
        }

        if (!weight || weight < 30 || weight > 200) {
            alert("请输入有效的体重 (30-200kg)");
            return;
        }

        // 计算BMI (体重kg / (身高m)^2)
        const heightInMeters = height / 100;
        const bmi = weight / (heightInMeters * heightInMeters);
        const roundedBmi = Math.round(bmi * 10) / 10;

        // 显示结果
        bmiValue.textContent = roundedBmi;

        // 确定BMI分类
        let category, tips;
        if (bmi < 18.5) {
            category = "偏瘦";
            tips =
                "您的体重偏轻，建议适当增加营养摄入，进行适度的力量训练来增加肌肉质量。";
        } else if (bmi >= 18.5 && bmi < 25) {
            category = "正常";
            tips = "恭喜！您的体重在健康范围内。继续保持均衡饮食和规律运动。";
        } else if (bmi >= 25 && bmi < 30) {
            category = "过重";
            tips =
                "您的体重略高，建议增加运动量，减少高热量食物摄入，保持健康饮食习惯。";
        } else {
            category = "肥胖";
            tips =
                "您的体重过高，可能增加健康风险。建议咨询医生或营养师，制定科学的减重计划。";
        }

        bmiCategory.textContent = category;

        // 更新指示器位置
        updateBmiIndicator(bmi);

        // 显示健康建议
        bmiTips.innerHTML = `
            <h4><i class="fas fa-lightbulb"></i> 健康建议</h4>
            <p>${tips}</p>
            <p><strong>BMI参考范围：</strong></p>
            <ul style="list-style-type: none;">
                <li>偏瘦：&lt; 18.5</li>
                <li>正常：18.5 - 24.9</li>
                <li>过重：25 - 29.9</li>
                <li>肥胖：≥ 30</li>
            </ul>
        `;

        // 显示结果区域
        bmiResult.style.display = "flex";
    }

    function updateBmiIndicator(bmi) {
        // 限制BMI在图表范围内 (15-40)
        const clampedBmi = Math.min(Math.max(bmi, 15), 40);

        // 计算指示器位置 (0-100%)
        let position;
        if (clampedBmi <= 18.5) {
            position = ((clampedBmi - 15) / (18.5 - 15)) * 25;
        } else if (clampedBmi <= 25) {
            position = 25 + ((clampedBmi - 18.5) / (25 - 18.5)) * 25;
        } else if (clampedBmi <= 30) {
            position = 50 + ((clampedBmi - 25) / (30 - 25)) * 25;
        } else {
            position = 75 + ((clampedBmi - 30) / (40 - 30)) * 25;
        }

        bmiIndicator.style.left = `${position}%`;
        bmiIndicator.style.display = "block";
    }

    function resetBMI() {
        heightInput.value = "";
        weightInput.value = "";
        bmiValue.textContent = "--";
        bmiCategory.textContent = "请先输入身高体重";
        bmiTips.innerHTML = `
            <h4><i class="fas fa-lightbulb"></i> 健康建议</h4>
            <p>请先计算您的BMI值以获取个性化建议</p>
        `;
        bmiIndicator.style.display = "none";
        bmiResult.style.display = "none";
    }

    // 单位换算器功能
    const converterTabs = document.querySelectorAll(".converter-tab");
    const converterPanes = document.querySelectorAll(".converter-pane");

    converterTabs.forEach((tab) => {
        tab.addEventListener("click", function () {
            // 移除所有活动标签
            converterTabs.forEach((t) => t.classList.remove("active"));
            converterPanes.forEach((p) => p.classList.remove("active"));

            // 激活当前标签
            this.classList.add("active");
            const type = this.getAttribute("data-type");
            document.getElementById(`${type}Pane`).classList.add("active");

            // 触发当前面板的换算
            convertUnits(type);
        });
    });

    // 为所有输入和选择框添加事件监听
    document
        .querySelectorAll(".converter-pane input, .converter-pane select")
        .forEach((element) => {
            element.addEventListener("input", function () {
                const pane = this.closest(".converter-pane");
                const type = pane.id.replace("Pane", "");
                convertUnits(type);
            });
        });

    function convertUnits(type) {
        const value =
            parseFloat(document.getElementById(`${type}Value`).value) || 0;
        const fromUnit = document.getElementById(`${type}From`).value;
        const toUnit = document.getElementById(`${type}To`).value;

        let result;

        switch (type) {
            case "length":
                result = convertLength(value, fromUnit, toUnit);
                break;
            case "weight":
                result = convertWeight(value, fromUnit, toUnit);
                break;
            case "volume":
                result = convertVolume(value, fromUnit, toUnit);
                break;
            case "temperature":
                result = convertTemperature(value, fromUnit, toUnit);
                break;
        }

        document.getElementById(`${type}Result`).value = result
            .toFixed(6)
            .replace(/\.?0+$/, "");
    }

    function convertLength(value, from, to) {
        // 先转换为米
        let meters;
        switch (from) {
            case "kilometer":
                meters = value * 1000;
                break;
            case "centimeter":
                meters = value / 100;
                break;
            case "millimeter":
                meters = value / 1000;
                break;
            case "inch":
                meters = value * 0.0254;
                break;
            case "foot":
                meters = value * 0.3048;
                break;
            case "yard":
                meters = value * 0.9144;
                break;
            case "mile":
                meters = value * 1609.344;
                break;
            default:
                meters = value; // 米
        }

        // 从米转换为目标单位
        switch (to) {
            case "kilometer":
                return meters / 1000;
            case "centimeter":
                return meters * 100;
            case "millimeter":
                return meters * 1000;
            case "inch":
                return meters / 0.0254;
            case "foot":
                return meters / 0.3048;
            case "yard":
                return meters / 0.9144;
            case "mile":
                return meters / 1609.344;
            default:
                return meters; // 米
        }
    }

    function convertWeight(value, from, to) {
        // 先转换为克
        let grams;
        switch (from) {
            case "kilogram":
                grams = value * 1000;
                break;
            case "milligram":
                grams = value / 1000;
                break;
            case "pound":
                grams = value * 453.59237;
                break;
            case "ounce":
                grams = value * 28.349523125;
                break;
            default:
                grams = value; // 克
        }

        // 从克转换为目标单位
        switch (to) {
            case "kilogram":
                return grams / 1000;
            case "milligram":
                return grams * 1000;
            case "pound":
                return grams / 453.59237;
            case "ounce":
                return grams / 28.349523125;
            default:
                return grams; // 克
        }
    }

    function convertVolume(value, from, to) {
        // 先转换为毫升
        let milliliters;
        switch (from) {
            case "liter":
                milliliters = value * 1000;
                break;
            case "gallon":
                milliliters = value * 3785.411784;
                break;
            case "quart":
                milliliters = value * 946.352946;
                break;
            case "pint":
                milliliters = value * 473.176473;
                break;
            case "cup":
                milliliters = value * 240;
                break;
            case "tablespoon":
                milliliters = value * 14.78676478125;
                break;
            case "teaspoon":
                milliliters = value * 4.92892159375;
                break;
            default:
                milliliters = value; // 毫升
        }

        // 从毫升转换为目标单位
        switch (to) {
            case "liter":
                return milliliters / 1000;
            case "gallon":
                return milliliters / 3785.411784;
            case "quart":
                return milliliters / 946.352946;
            case "pint":
                return milliliters / 473.176473;
            case "cup":
                return milliliters / 240;
            case "tablespoon":
                return milliliters / 14.78676478125;
            case "teaspoon":
                return milliliters / 4.92892159375;
            default:
                return milliliters; // 毫升
        }
    }

    function convertTemperature(value, from, to) {
        // 先转换为摄氏度
        let celsius;
        switch (from) {
            case "fahrenheit":
                celsius = ((value - 32) * 5) / 9;
                break;
            case "kelvin":
                celsius = value - 273.15;
                break;
            default:
                celsius = value; // 摄氏度
        }

        // 从摄氏度转换为目标单位
        switch (to) {
            case "fahrenheit":
                return (celsius * 9) / 5 + 32;
            case "kelvin":
                return celsius + 273.15;
            default:
                return celsius; // 摄氏度
        }
    }

    // 初始化第一个标签页的换算
    convertUnits("length");

    // 时间管理工具功能
    const timeTabs = document.querySelectorAll(".time-tab");
    const timePanes = document.querySelectorAll(".time-pane");

    timeTabs.forEach((tab) => {
        tab.addEventListener("click", function () {
            // 移除所有活动标签
            timeTabs.forEach((t) => t.classList.remove("active"));
            timePanes.forEach((p) => p.classList.remove("active"));

            // 激活当前标签
            this.classList.add("active");
            const tool = this.getAttribute("data-tool");
            document.getElementById(`${tool}Pane`).classList.add("active");
        });
    });

    // 番茄钟功能
    let pomodoroInterval;
    let pomodoroTimeLeft = 25 * 60; // 25分钟
    let pomodoroPhase = "work"; // work or break
    let completedPomodoros = 0;

    const pomodoroTimeDisplay = document.getElementById("pomodoroTime");
    const pomodoroStartBtn = document.getElementById("pomodoroStart");
    const pomodoroPauseBtn = document.getElementById("pomodoroPause");
    const pomodoroResetBtn = document.getElementById("pomodoroReset");
    const pomodoroPhaseDisplay = document.getElementById("pomodoroPhase");
    const completedPomodorosDisplay =
        document.getElementById("completedPomodoros");
    const workDurationInput = document.getElementById("workDuration");
    const breakDurationInput = document.getElementById("breakDuration");

    pomodoroStartBtn.addEventListener("click", startPomodoro);
    pomodoroPauseBtn.addEventListener("click", pausePomodoro);
    pomodoroResetBtn.addEventListener("click", resetPomodoro);

    function startPomodoro() {
        pomodoroStartBtn.disabled = true;
        pomodoroPauseBtn.disabled = false;

        pomodoroTimeLeft = parseInt(workDurationInput.value) * 60;
        updatePomodoroDisplay();
        
        pomodoroInterval = setInterval(() => {
            pomodoroTimeLeft--;
            updatePomodoroDisplay();

            if (pomodoroTimeLeft <= 0) {
                clearInterval(pomodoroInterval);
                if (pomodoroPhase === "work") {
                    // 工作结束，开始休息
                    completedPomodoros++;
                    completedPomodorosDisplay.textContent = completedPomodoros;
                    pomodoroPhase = "break";
                    pomodoroTimeLeft = parseInt(breakDurationInput.value) * 60;
                    pomodoroPhaseDisplay.textContent = "休息时间";
                } else {
                    // 休息结束，开始工作
                    pomodoroPhase = "work";
                    pomodoroTimeLeft = parseInt(workDurationInput.value) * 60;
                    pomodoroPhaseDisplay.textContent = "工作时间";
                }

                // 自动开始下一阶段
                startPomodoro();
            }
        }, 1000);
    }

    function pausePomodoro() {
        clearInterval(pomodoroInterval);
        pomodoroStartBtn.disabled = false;
        pomodoroPauseBtn.disabled = true;
    }

    function resetPomodoro() {
        clearInterval(pomodoroInterval);
        pomodoroPhase = "work";
        pomodoroTimeLeft = parseInt(workDurationInput.value) * 60;
        pomodoroPhaseDisplay.textContent = "准备开始工作";
        pomodoroStartBtn.disabled = false;
        pomodoroPauseBtn.disabled = true;
        updatePomodoroDisplay();
    }

    function updatePomodoroDisplay() {
        const minutes = Math.floor(pomodoroTimeLeft / 60);
        const seconds = pomodoroTimeLeft % 60;
        pomodoroTimeDisplay.textContent = `${minutes
            .toString()
            .padStart(2, "0")}:${seconds.toString().padStart(2, "0")}`;
    }

    // 秒表功能
    let stopwatchInterval;
    let stopwatchTime = 0;
    let stopwatchRunning = false;
    let lapCount = 1;

    const stopwatchTimeDisplay = document.getElementById("stopwatchTime");
    const stopwatchStartBtn = document.getElementById("stopwatchStart");
    const stopwatchPauseBtn = document.getElementById("stopwatchPause");
    const stopwatchResetBtn = document.getElementById("stopwatchReset");
    const stopwatchLapBtn = document.getElementById("stopwatchLap");
    const stopwatchLapsContainer = document.getElementById("stopwatchLaps");

    stopwatchStartBtn.addEventListener("click", startStopwatch);
    stopwatchPauseBtn.addEventListener("click", pauseStopwatch);
    stopwatchResetBtn.addEventListener("click", resetStopwatch);
    stopwatchLapBtn.addEventListener("click", recordLap);

    function startStopwatch() {
        if (!stopwatchRunning) {
            stopwatchRunning = true;
            stopwatchStartBtn.disabled = true;
            stopwatchPauseBtn.disabled = false;
            stopwatchLapBtn.disabled = false;

            const startTime = Date.now() - stopwatchTime;
            stopwatchInterval = setInterval(() => {
                stopwatchTime = Date.now() - startTime;
                updateStopwatchDisplay();
            }, 10);
        }
    }

    function pauseStopwatch() {
        stopwatchRunning = false;
        clearInterval(stopwatchInterval);
        stopwatchStartBtn.disabled = false;
        stopwatchPauseBtn.disabled = true;
        stopwatchLapBtn.disabled = true;
    }

    function resetStopwatch() {
        pauseStopwatch();
        stopwatchTime = 0;
        lapCount = 1;
        updateStopwatchDisplay();
        stopwatchLapsContainer.innerHTML =
            '<div class="laps-header"><span>计次</span><span>时间</span></div>';
    }

    function recordLap() {
        const lapItem = document.createElement("div");
        lapItem.className = "lap-item";
        lapItem.innerHTML = `
            <span>计次 ${lapCount}</span>
            <span>${formatStopwatchTime(stopwatchTime)}</span>
        `;
        stopwatchLapsContainer.appendChild(lapItem);
        lapCount++;
    }

    function updateStopwatchDisplay() {
        stopwatchTimeDisplay.textContent = formatStopwatchTime(stopwatchTime);
    }

    function formatStopwatchTime(time) {
        const hours = Math.floor(time / 3600000);
        const minutes = Math.floor((time % 3600000) / 60000);
        const seconds = Math.floor((time % 60000) / 1000);
        const milliseconds = Math.floor((time % 1000) / 10);

        return `${hours
            .toString()
            .padStart(
                2,
                "0"
            )}:${minutes.toString().padStart(2, "0")}:${seconds.toString().padStart(2, "0")}.${milliseconds.toString().padStart(2, "0")}`;
    }

    // 倒计时功能
    let countdownInterval;
    let countdownTime = 0;
    let countdownRunning = false;

    const countdownTimeDisplay = document.getElementById("countdownTime");
    const countdownStartBtn = document.getElementById("countdownStart");
    const countdownPauseBtn = document.getElementById("countdownPause");
    const countdownResetBtn = document.getElementById("countdownReset");
    const countdownHoursInput = document.getElementById("countdownHours");
    const countdownMinutesInput = document.getElementById("countdownMinutes");
    const countdownSecondsInput = document.getElementById("countdownSeconds");

    countdownStartBtn.addEventListener("click", startCountdown);
    countdownPauseBtn.addEventListener("click", pauseCountdown);
    countdownResetBtn.addEventListener("click", resetCountdown);

    function startCountdown() {
        if (!countdownRunning) {
            // 如果倒计时未开始，从输入框获取时间
            if (countdownTime <= 0) {
                const hours = parseInt(countdownHoursInput.value) || 0;
                const minutes = parseInt(countdownMinutesInput.value) || 0;
                const seconds = parseInt(countdownSecondsInput.value) || 0;
                countdownTime = hours * 3600 + minutes * 60 + seconds;

                if (countdownTime <= 0) {
                    alert("请设置有效的倒计时时间");
                    return;
                }
            }

            countdownRunning = true;
            countdownStartBtn.disabled = true;
            countdownPauseBtn.disabled = false;

            countdownInterval = setInterval(() => {
                countdownTime--;
                updateCountdownDisplay();

                if (countdownTime <= 0) {
                    clearInterval(countdownInterval);
                    countdownRunning = false;
                   
                    countdownStartBtn.disabled = false;
                    countdownPauseBtn.disabled = true;
                }
            }, 1000);
        }
    }

    function pauseCountdown() {
        countdownRunning = false;
        clearInterval(countdownInterval);
        countdownStartBtn.disabled = false;
        countdownPauseBtn.disabled = true;
    }

    function resetCountdown() {
        pauseCountdown();
        countdownTime = 0;
        updateCountdownDisplay();
    }

    function updateCountdownDisplay() {
        const hours = Math.floor(countdownTime / 3600);
        const minutes = Math.floor((countdownTime % 3600) / 60);
        const seconds = countdownTime % 60;

        countdownTimeDisplay.textContent = `${hours
            .toString()
            .padStart(2, "0")}:${minutes.toString().padStart(2, "0")}:${seconds
            .toString()
            .padStart(2, "0")}`;
    }

    
});    